package com.dkd.sbtz.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.dkd.common.core.domain.TreeSelect;
import com.dkd.common.core.domain.entity.SysDept;
import com.dkd.common.core.domain.entity.SysUser;
import com.dkd.common.core.page.PageDomain;
import com.dkd.common.core.page.TableSupport;
import com.dkd.common.utils.PageUtils;
import com.dkd.common.utils.SecurityUtils;
import com.dkd.common.utils.sql.SqlUtil;
import com.dkd.sbtz.domain.AssetNodeUsage;
import com.dkd.sbtz.domain.vo.*;
import com.dkd.sbtz.domain.vo.nodeImport.AssetImportRow;
import com.dkd.sbtz.domain.vo.nodeImport.SbtzExtImportDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.sbtz.domain.Sbtz;
import com.dkd.sbtz.service.ISbtzService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备台账Controller
 * 
 * @author xzj
 * @date 2025-09-02
 */
@Slf4j
@RestController
@RequestMapping("/sbtz/sbtz")
public class SbtzController extends BaseController
{
    @Autowired
    private ISbtzService sbtzService;

    @PostMapping("/route/create")
    public AjaxResult createRoute(@RequestBody RouteCreateDTO dto) {
        String username = SecurityUtils.getUsername(); // 若依获取当前用户；没有可写固定值
        List<Long> ids = sbtzService.createRoute(dto, username);
        return AjaxResult.success().put("ids", ids);
    }


    @PostMapping("/machine/create")
    public AjaxResult createMachines(@RequestBody RouteCreateDTO dto) {
        String username = SecurityUtils.getUsername();
        List<Long> ids = sbtzService.createMachines(dto, username);
        return AjaxResult.success("母设备创建成功", ids);
    }


    @GetMapping("/list")
    public TableDataInfo list(Sbtz sbtz) {
        PageDomain pd = TableSupport.buildPageRequest();
        String orderBy = buildSafeOrderBy(pd.getOrderByColumn(), pd.getIsAsc());

        // 只在这里设置分页和排序；Mapper XML 不要写 ORDER BY / LIMIT
        PageUtils.startPage(pd.getPageNum(), pd.getPageSize(), orderBy);

        List<Sbtz> list = sbtzService.selectSbtzListVO(sbtz);

        // ★ 关键：不要再 new ArrayList<>(list)，直接把原 list 传进去
        return getDataTable(list);
    }

    private String buildSafeOrderBy(String col, String dir) {
        col = SqlUtil.escapeOrderBySql(col);
        Map<String,String> map = new HashMap<>();
        // 前端列 prop  ->  数据库真实列（注意别名，与 XML 的 FROM 别名要一致）
        map.put("createTime", "n.create_time");
        map.put("updateTime", "n.update_time");
        map.put("name",       "n.name");
        map.put("code",       "n.code");
        map.put("id",         "n.id");
        map.put("beTypeFirst", "n.be_type_first");

        String safeCol = map.getOrDefault(col, "n.id");
        String safeDir = "desc";
//        String safeDir = "asc".equalsIgnoreCase(dir) ? "asc" : "desc";
        return safeCol + " " + safeDir + ", n.id " + safeDir; // 稳定次序
    }




    /*根据关键字查找id  并根据id查找到最终父id*/
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:list')")
    @GetMapping("/listSearchData")
    public TableDataInfo searchData(Sbtz sbtz) {
        startPage();                    // 这一句只会作用到 Service 里的 “第一个Mapper查询”
        List<AssetNodeListVO> list = sbtzService.selectSearchData(sbtz);
        return getDataTable(list);      // 若依标准返回
    }

    /**
     * 导出设备台账列表
     */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:export')")
    @Log(title = "设备台账", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
//    public void export(HttpServletResponse response, Sbtz sbtz)
//    {
//        List<Sbtz> list = sbtzService.selectSbtzList(sbtz);
//        ExcelUtil<Sbtz> util = new ExcelUtil<Sbtz>(Sbtz.class);
//        util.exportExcel(response, list, "设备台账数据");
//    }
    public void export(HttpServletResponse response, Sbtz query) {
        // 导出通常不分页：取全量满足条件的数据
        List<AssetNodeExportVO> list = sbtzService.selectForExport(query);
        ExcelUtil<AssetNodeExportVO> util = new ExcelUtil<>(AssetNodeExportVO.class);
        util.exportExcel(response, list, "资产节点导出");
    }


    @Log(title="设备台账报表", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:export')")
    @PostMapping("/exportChain")
    public void exportChain(HttpServletResponse response, Sbtz query) {
        List<ExportWithParentVO> rows = sbtzService.selectChainRowsForExport(query);
        ExcelUtil<ExportWithParentVO> util = new ExcelUtil<>(ExportWithParentVO.class);
        util.exportExcel(response, rows, "完整父级链_含自身（多行）");
    }


    /**
     * 获取设备台账详细信息
     */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sbtzService.selectSbtzById(id));
    }

    /**
     * 新增设备台账
     */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:add')")
    @Log(title = "设备台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Sbtz sbtz)
    {
        return toAjax(sbtzService.insertSbtz(sbtz));
    }

    /**
     * 修改设备台账
     */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:edit')")
    @Log(title = "设备台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Sbtz sbtz)
    {
        return toAjax(sbtzService.updateSbtz(sbtz));
    }

    /**
     * 删除设备台账
     */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:remove')")
    @Log(title = "设备台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/batch/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sbtzService.deleteSbtzByIds(ids));
    }


    @GetMapping("/picker/children")
    public AjaxResult children(@RequestParam(required = false, defaultValue = "0") Long parentId) {
        // RuoYi: 统一返回 { code, msg, data }
        return AjaxResult.success(sbtzService.children(parentId));
    }

    /*修改节点所属操作,包含删除操作，先删再增*/
    @PostMapping("/route/rehome")
    public AjaxResult rehome(@RequestBody @Valid RehomeByRecreateDTO dto) {
        String user = SecurityUtils.getUsername();
        Long id = sbtzService.rehomeByRecreate(dto, user);
        return AjaxResult.success("移动并更新成功").put("id", id);
    }


    @DeleteMapping("/{id}")
    public AjaxResult deleteSubtree(@PathVariable("id") Long id,
                                    @RequestHeader(name = "X-User", required = false) String operUser) {
        String user = SecurityUtils.getUsername();
        int affected = sbtzService.deleteSubtree(id, user);

        Map<String, Object> resp = new HashMap<>();
        resp.put("nodeId", id);
        resp.put("affected", affected);

//        log.info("info asset nodes, ids={}", id);
//        log.trace("trace method, args={}", id);
//        log.debug("debug params: {}", id);
//        log.info("info");
//        log.warn("warn");
//        log.error("error");

        return AjaxResult.success(resp); // ✅
    }


    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:query')")
    @GetMapping("/treeSelect")
    public AjaxResult treeSelect(Sbtz query) {
        // 不要 startPage()
        List<TreeSelect> list = sbtzService.selectAssetTreeList(query);
        // RuoYi 统一返回
        return success(list);
    }




    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/dept/usage/{id}")
    public TableDataInfo getDeptUsageList(@PathVariable("id") Long id)
    {
        startPage();
        List<AssetNodeUsage> list = sbtzService.selectNodeUsageById(id);
        return getDataTable(list);
    }







    /**
     * 导入模板（只含这八列）
     */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:import')")
    @Log(title = "设备台账-扩展字段导入模板", businessType = BusinessType.EXPORT)
    @GetMapping("/importExtTemplate")
    public AjaxResult importExtTemplate() {
        ExcelUtil<SbtzExtImportDTO> util = new ExcelUtil<>(SbtzExtImportDTO.class);
        return util.importTemplateExcel("设备扩展字段导入模板");
    }

    /**
     * 导入并更新
     * @param onlyWhenSpecEmpty 是否仅在数据库中 specification 为空(或空串)时才更新
     * @param ignoreBlank       是否忽略 Excel 里的空白值（true=忽略，不覆盖；false=覆盖为空）
     */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:import')")
    @Log(title = "设备台账-扩展字段导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importExt")
    public AjaxResult importExt(@RequestParam("file") MultipartFile file,
                                @RequestParam(value = "onlyWhenSpecEmpty", required = false, defaultValue = "false") boolean onlyWhenSpecEmpty,
                                @RequestParam(value = "ignoreBlank", required = false, defaultValue = "true") boolean ignoreBlank)
            throws Exception {

        ExcelUtil<SbtzExtImportDTO> util = new ExcelUtil<>(SbtzExtImportDTO.class);
        List<SbtzExtImportDTO> rows = util.importExcel(file.getInputStream());

        // 让 Service 做校验、去重、统计与更新
        String report = sbtzService.importExtFields(rows, onlyWhenSpecEmpty, ignoreBlank);

        return AjaxResult.success(report);
    }




    /*测试导入excel数据*/
    /** 导入Excel */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:import')")
    @Log(title = "设备批量导入", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/excel", consumes = "multipart/form-data")
    public AjaxResult importExcel(@RequestPart("file") MultipartFile file) throws Exception {
        return AjaxResult.success(sbtzService.importExcel(file));
    }

//    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:import')")
//    @PostMapping("/template")
//    public AjaxResult importTemplate() {
//        ExcelUtil<AssetImportRow> util = new ExcelUtil<>(AssetImportRow.class);
//        // 返回 { code:200, msg: 生成的文件名 }，前端 download 会去 /common/download?fileName=... 拉取
//        return util.importTemplateExcel("设备导入模板");
//    }

    @PreAuthorize("@ss.hasPermi('sbtz:sbtz:import')")
    @GetMapping("/template")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<AssetImportRow> util = new ExcelUtil<>(AssetImportRow.class);
        util.importTemplateExcel(response, "设备导入模板"); // 你项目里的 ExcelUtil 若有该重载
    }


    /*测试导入excel数据end*/





    @GetMapping("/getTreePath/{id}")
    public AjaxResult path(@PathVariable("id") Long id) {
        return AjaxResult.success(sbtzService.getPathByLeaf(id));
    }



    @GetMapping("/checkBeTypeFirst")
    public AjaxResult checkExists(@RequestParam Map<String, Object> params) {
        boolean exists = sbtzService.checkBeTypeFirst(params);
        return AjaxResult.success(Map.of("exists", exists));
    }
}
